<template>
  <div class="product-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="searchForm.brandId" placeholder="请选择品牌" clearable>
            <el-option label="耐克" value="1" />
            <el-option label="阿迪达斯" value="2" />
            <el-option label="李宁" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.categoryId" placeholder="请选择类型" clearable>
            <el-option label="运动鞋" value="1" />
            <el-option label="休闲鞋" value="2" />
            <el-option label="皮鞋" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="产地">
          <el-input v-model="searchForm.producer" placeholder="请输入产地" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-card class="product-list-card">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增商品
          </el-button>
        </div>
      </template>

      <el-table 
        :data="productList" 
        style="width: 100%" 
        v-loading="loading"
        :max-height="600"
        stripe>
        <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="image" label="商品图片" width="120">
          <template #default="scope">
            <img :src="scope.row.image" alt="商品图片" class="productImage" />
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" width="100" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="类型" width="100" show-overflow-tooltip />
        <el-table-column prop="discount" label="折扣价" width="100">
          <template #default="scope">
            <span style="color: #e74c3c; font-weight: bold;">¥{{ scope.row.discount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="timessold" label="销量" width="80" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="producer" label="产地" width="100" show-overflow-tooltip />
        <el-table-column prop="remarks" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column prop="createTime" label="发布时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              size="small"
              @click="handleToggleStatus(scope.row)"
              :type="scope.row.status === 1 ? 'danger' : 'success'">
              <el-icon><Switch /></el-icon>
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商品' : '编辑商品'"
      width="600px"
      @close="handleDialogClose">
      <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="100px">
        <el-form-item label="商品编号" prop="code">
          <el-input v-model="productForm.code" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="productForm.brandId" placeholder="请选择品牌">
            <el-option label="耐克" value="1" />
            <el-option label="阿迪达斯" value="2" />
            <el-option label="李宁" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-select v-model="productForm.color" placeholder="请选择颜色">
            <el-option label="黑色" value="1" />
            <el-option label="白色" value="2" />
            <el-option label="红色" value="3" />
            <el-option label="蓝色" value="4" />
            <el-option label="灰色" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择类型">
            <el-option label="运动鞋" value="1" />
            <el-option label="休闲鞋" value="2" />
            <el-option label="皮鞋" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="原价" prop="price">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="折扣价" prop="discount">
          <el-input-number v-model="productForm.discount" :min="0" :precision="2" placeholder="请输入折扣价" />
        </el-form-item>
        <el-form-item label="销量" prop="timessold">
          <el-input-number v-model="productForm.timessold" :min="0" :precision="0" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="产地" prop="producer">
          <el-input v-model="productForm.producer" placeholder="请输入产地" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="productForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="productForm.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="productForm.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
        </el-form-item>
        <!-- 商品图片上传 -->
        <el-form-item label="商品图片">
          <div class="productImage-uploader">
            <el-upload
              class="productImage-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleChangeFile"
            >
                <img v-if="productForm.image" :src="productForm.image" class="productImage" />       
              <el-icon v-else class="productImage-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Plus, Edit, Delete, Switch
} from '@element-plus/icons-vue'
import {findAllProducts,updateProduct,deleteProduct,addProduct,updateShoesDelete} from '@/api/product'
import { uploadFileReq } from '@/api/product'

onMounted(()=>{
  FindAllProducts() // 这个函数会异步加载数据，完成后会自动更新productList
})

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  brandId: '',
  categoryId: '',
  gender: '',
  producer: ''
})

const productImage = ref('');
// 商品列表数据
const productList = ref([])
const allProductList = ref([]) // 存储所有商品数据，用于本地搜索
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const productFormRef = ref()

// 商品表单
const productForm = reactive({
  id: '',
  code: '',
  name: '',
  brandId: '',
  categoryId: '',
  color: '',
  price: 0,
  discount: 0,
  timessold: 0,
  producer: '',
  gender: '',
  remarks: '',
  description: '',
  image: ''
})

// 文件列表
const fileList = ref([])

// 表单验证规则
const productRules = {
  code: [
    { required: true, message: '请输入商品编号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  brandId: [
    { required: true, message: '请选择品牌', trigger: 'change' }
  ],
  color: [
    { required: true, message: '请选择颜色', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0, message: '原价必须大于等于0', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣价', trigger: 'blur' },
    { type: 'number', min: 0, message: '折扣价必须大于等于0', trigger: 'blur' }
  ],
  timessold: [
    { required: true, message: '请输入销量', trigger: 'blur' },
    { type: 'number', min: 0, message: '销量必须大于等于0', trigger: 'blur' }
  ],
  producer: [
    { required: true, message: '请输入产地', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

const FindAllProducts = async () => {
  try {
    loading.value = true
    const res = await findAllProducts()
  
    if (!res || res.status !== 200) {
      ElMessage.error(res?.message || '获取商品列表失败')
      return
    }
    
    if (!res.data || !Array.isArray(res.data)) {
      ElMessage.error('数据格式错误')
      return
    }
    
    if (res.data.length === 0) {
      ElMessage.warning('暂无商品数据')
      allProductList.value = []
      productList.value = []
      total.value = 0
      return
    }
    
    const mappedData = res.data.map(item => ({
      id: item.sid,
      code: item.snum,
      name: item.sname,
      price: item.sprices,
      discount: item.sdiscount,
      pubtime: item.spubtime,
      producer: item.sproducer,
      gender: item.sgender,
      color: item.scid,        // 鞋子颜色
      categoryId: item.typeId,    // 类型ID
      info: item.sinfo,
      timessold: item.stimessold,
      image: item.simage,
      detail: item.sdetail,
      integral: item.sintegral,
      delete: item.sdelete,
      remarks: item.sremarks,
      androidimg: item.sandroidimg,
      typeId: item.typeId,        // 类型ID
      brandId: item.brandId,
      status: item.sdelete === 0 ? 1 : 0,  // 前端status: 1=上架，0=下架
      createTime: item.spubtime,
      brandName: getBrandName(item.brandId),
      categoryName: getCategoryName(item.typeId)
    }))
    
    allProductList.value = mappedData
    total.value = mappedData.length
    getProductList()
    
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取商品列表（本地搜索和分页）
const getProductList = () => {
  loading.value = true
  
  if (!allProductList.value || allProductList.value.length === 0) {
    productList.value = []
    total.value = 0
    loading.value = false
    return
  }
  
  let result = [...allProductList.value]
  
  // 搜索过滤
  if (searchForm.name) {
    result = result.filter(product => product.name && product.name.includes(searchForm.name))
  }
  if (searchForm.code) {
    result = result.filter(product => product.code && product.code.includes(searchForm.code))
  }
  if (searchForm.brandId) {
    result = result.filter(product => String(product.brandId) === String(searchForm.brandId))
  }
  if (searchForm.categoryId) {
    result = result.filter(product => String(product.categoryId) === String(searchForm.categoryId))
  }
  if (searchForm.gender) {
    result = result.filter(product => product.gender === searchForm.gender)
  }
  if (searchForm.producer) {
    result = result.filter(product => product.producer && product.producer.includes(searchForm.producer))
  }
  
  // 分页
  total.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  productList.value = result.slice(start, end)
  
  loading.value = false
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getProductList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.brandId = ''
  searchForm.categoryId = ''
  searchForm.gender = ''
  searchForm.producer = ''
  handleSearch()
}

// 新增商品
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(productForm, {
    id: row.id,
    code: row.code,
    name: row.name,
    brandId: row.brandId,
    categoryId: row.categoryId,
    color: row.color,        // 鞋子颜色
    price: row.price,
    discount: row.discount,
    timessold: row.timessold,
    producer: row.producer,
    gender: row.gender,
    remarks: row.remarks,
    description: row.info || ''
  })
  dialogVisible.value = true
}
//头像缩略图数据模型
  function handleChangeFile(uploadFile){
      //获得当前选中的图片对象
      let file = uploadFile.raw;
      //将file的图片地址 赋值给缩略图数据模型
      productForm.image = URL.createObjectURL(file)
      //上传逻辑
      uploadFileFunc(file);
  }
  function uploadFileFunc(file){
    //创建虚拟表单 用于装载上传文件
    let formData = new FormData();
    formData.append("file",file);

    // //发送图片
    uploadFileReq(formData)
    .then(data =>{
        //上传成功 将上传图片的url赋值给数据模型
        console.log(data.message)
        productImage.value = data.message;
    })
  }

// 切换商品状态
const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '下架' : '上架'
  ElMessageBox.confirm(
    `确定要${action}商品 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      
      if (action === '下架') {
        // 使用专门的updateShoesDelete API处理下架逻辑
        const res = await updateShoesDelete(row.id)
        
        if (res && res.status === 200) {
          row.status = 0  // 前端status: 0=下架，1=上架
          ElMessage.success('下架成功')
        } else {
          ElMessage.error(res?.message || '下架失败')
        }
      } else {
        // 上架操作仍使用通用的updateProduct API
        const newStatus = 0  // 0=上架，1=下架
        
        // 调用更新API - 映射为数据库字段
        const updateData = {
          sid: row.id,              // 商品ID
          snum: row.code,           // 商品编号
          sname: row.name,          // 商品名称
          sprices: row.price,       // 原价
          sdiscount: row.discount,  // 折扣价
          stimessold: row.timessold, // 销量
          sproducer: row.producer,  // 产地
          sgender: row.gender,      // 性别
          scid: row.color || row.categoryId,     // 鞋子颜色
          typeId: row.categoryId,      // 类型ID
          sinfo: row.info,          // 商品描述
          sremarks: row.remarks,    // 备注
          brandId: row.brandId,     // 品牌ID
          sdelete: newStatus,        // 状态：0=上架，1=下架
          //simage: productImage.value,  // 商品图片
        }
        
        const res = await updateProduct(updateData)
        
        if (res && res.status === 200) {
          row.status = 1  // 前端status: 1=上架，0=下架
          ElMessage.success('上架成功')
        //  productImage.value = ''
        } else {
          ElMessage.error(res?.message || '上架失败')
        }
      }
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 删除商品
const handleDelete = async (row) => {
  ElMessageBox.confirm(
    `确定要删除商品 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      const res = await deleteProduct(row.id)
      
      if (res && res.status === 200) {
        // 从本地列表中删除
        const index = productList.value.findIndex(product => product.id === row.id)
        if (index > -1) {
          productList.value.splice(index, 1)
        }
        // 同时从 allProductList 中删除
        const allIndex = allProductList.value.findIndex(product => product.id === row.id)
        if (allIndex > -1) {
          allProductList.value.splice(allIndex, 1)
          total.value = allProductList.value.length
        }
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        if (dialogType.value === 'add') {
          // 新增商品 - 映射为数据库字段
          const addData = {
            snum: productForm.code,      // 商品编号
            sname: productForm.name,     // 商品名称
            sprices: productForm.price,  // 原价
            sdiscount: productForm.discount, // 折扣价
            stimessold: productForm.timessold, // 销量
            sproducer: productForm.producer, // 产地
            sgender: productForm.gender,     // 性别
            scid: productForm.color,       // 鞋子颜色
            typeId: productForm.categoryId,     // 类型ID
            sinfo: productForm.description,  // 商品描述
            sremarks: productForm.remarks,     // 备注
            brandId: productForm.brandId,    // 品牌ID
            sdelete: 0  // 默认上架状态
          }
          
          const res = await addProduct(addData)
          
          if (res && res.status === 200) {
            ElMessage.success('新增商品成功')
            // 重新获取商品列表
            await FindAllProducts()
          } else {
            ElMessage.error(res?.message || '新增失败')
            return
          }
        } else {
          // 编辑商品 - 映射为数据库字段
          const updateData = {
            sid: productForm.id,         // 商品ID
            snum: productForm.code,      // 商品编号
            sname: productForm.name,     // 商品名称
            sprices: productForm.price,  // 原价
            sdiscount: productForm.discount, // 折扣价
            stimessold: productForm.timessold, // 销量
            sproducer: productForm.producer, // 产地
            sgender: productForm.gender,     // 性别
            scid: productForm.color,       // 鞋子颜色
            typeId: productForm.categoryId,     // 类型ID
            sinfo: productForm.description,  // 商品描述
            sremarks: productForm.remarks,     // 备注
            brandId: productForm.brandId,    // 品牌ID
            sdelete: 0,  // 保持上架状态
            simage: productImage.value,  // 商品图片
          }
          
          const res = await updateProduct(updateData)
          
          if (res && res.status === 200) {
            ElMessage.success('编辑商品成功')
            // 重新获取商品列表
            productImage.value = ''
            await FindAllProducts()
          } else {
            ElMessage.error(res?.message || '编辑失败')
            return
          }
        }
        
        dialogVisible.value = false
        handleReset()
        
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 获取品牌名称
const getBrandName = (brandId) => {
  const brandMap = {
    '1': '耐克',
    '2': '阿迪达斯',
    '3': '李宁'
  }
  return brandMap[brandId] || ''
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const categoryMap = {
    '1': '运动鞋',
    '2': '休闲鞋',
    '3': '皮鞋'
  }
  return categoryMap[categoryId] || ''
}

// 关闭对话框
const handleDialogClose = () => {
  productFormRef.value?.resetFields()
  Object.assign(productForm, {
    id: '',
    code: '',
    name: '',
    brandId: '',
    categoryId: '',
    color: '',
    price: 0,
    discount: 0,
    timessold: 0,
    producer: '',
    gender: '',
    remarks: '',
    description: '',
    image: ''
  })
  fileList.value = []
}


// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getProductList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getProductList()
}
</script>

<style scoped>
/* 图片上传容器样式：控制整体大小、边框、布局 */
.productImage-uploader {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
  cursor: pointer;
}

/* 上传容器 hover 效果：增强交互反馈 */
.productImage-uploader:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

/* 商品图片预览样式：确保图片填充容器且不变形 */
.productImage {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例，填充容器（裁剪超出部分） */
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

/* 加号图标样式：控制图标大小和颜色 */
.productImage-uploader-icon {
  font-size: 24px;
  color: #c0c4cc;
  transition: color 0.3s ease;
}

/* 图标 hover 颜色变化：与容器 hover 效果呼应 */
.productImage-uploader:hover .productImage-uploader-icon {
  color: #409eff;
}

/* 确保上传触发区域完全覆盖容器（避免点击空白） */
.productImage-uploader .el-upload {
  display: block;
  width: 100%;
  height: 100%;
}
.product-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.product-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-demo {
  width: 100%;
}
</style>